<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/7/12 0012
 * Time: 下午 5:08
 */

namespace common\components;


class ValidateCodeRedis extends ValidateCode
{
    public function sendCode($scenarioKey, $redisPrefix = "", $expire = 300)
    {
        \Yii::$app->response->headers->set("X-code-token", $scenarioKey);
        \Yii::$app->response->send();

        $this->doimg();
        $redis = \Yii::$app->redis;

        if ( $redisPrefix ) {
            $scenarioKey = $redisPrefix . ":" . $scenarioKey;
        }
        $redis->set($scenarioKey, $this->getCode());
        $redis->expire($scenarioKey, $expire);
    }

    public static function validate($scenarioKey, $captcha, $redisPrefix = "", $isDel = true)
    {
        if ( $redisPrefix ) {
            $scenarioKey = $redisPrefix . ":" . $scenarioKey;
        }

        $redis = \Yii::$app->redis;
        $code = $redis->get($scenarioKey);
        if ( !$code || strtolower($code) != strtolower($captcha) ) {
            return false;
        }
        $isDel && $redis->del($scenarioKey);
        return true;
    }
}